<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/
class share_api{

	public function getViewCount(){
		if($result = pcache('r', 'share_count')){
			return $result;
		}

		$sharedb = load_db('share');
		$result['click'] = $sharedb->view_count();
		$result['like'] = $sharedb->like_count();
		$result['share'] = $sharedb->share_count();
		$result['forwarding'] = $sharedb->forwarding_count();
		$setting = load_api('setting');
		$cachetime = $setting->getCacheTime();
		pcache('w','share_count',$result,$cachetime?$cachetime['cachetime_count']:3600);

		return $result;
	}


	public function countByCategory($cid){
		return load_db('share')->findCount(array('category_id'=>$cid));
	}

	public function countByCategories($cids){
		$cond = array();
		foreach ($cids as $s) {
			$cond[] = ' (ptx_share.category_id IN ('.$s.')) ';
		}
		$conditions_share = join(" OR ",$cond);
		return load_db('share')->findCount($conditions_share);
	}

	public function updateshare($share_id,$data){
		return load_db('share')->update(array('share_id'=>$share_id),$data);
	}


	public function updateDBItem($itemid,$data){
		return load_db('share/item')->update(array('item_id'=>$itemid),$data);
	}

	public function getTopShares($cid=0){
		if($cid){
			$conditions['category_id'] = $cid;
			$conditions['dtype_in']=array('2','3');
		}else{
			$conditions['dtype']=2;
		}
		return load_db('share')->search_no_page($conditions);
	}

	public function getRoundByCategory($category_id,$limit){
		return load_db('share')->get_round($category_id,$limit);
	}

	public function prepareShares($shares){
		$settingapi = load_api('setting');
		$setting = load_api('setting')->getSetting('upload');
		$pinsetting = $settingapi->getSetting('layoutpin');
		$this->comment_num = $pinsetting['uipin_numcomment']?$pinsetting['uipin_numcomment']:0;
		$this->wftwidth = $setting['wftwidth'];
		$this->colorsetting = $settingapi->getSetting('colorindex');
		$this->uimuilt = $pinsetting['uipin_multi'];
		$this->pz = &get_instance();
		$sids = array();
		if($this->pz->islogin){
			foreach ($shares as $share){
				if($share['user_id']!=$this->pz->cuser['uid']){
					$sids[] = $share['share_id'];
				}
			}
			if(array_length($sids)>0){
				$conditions['sids'] = $sids;
				$conditions['user_id'] = $this->pz->cuser['uid'];
				$favsharedb = load_db('share/favshare');
				$favsids = $favsharedb->search_nopage($conditions,' ptx_favorite_sharing.share_id ');
			}
		}
		foreach ($shares as $key=>$share){
			$tmpshare = $this->prepareshare($share);
			if($favsids&&$this->checkfav($share, $favsids)){
				$tmpshare['liked'] = true;
			}
			$shares[$key] = $tmpshare;
		}
		return $shares;
	}

	public function checkonesharefav($share){
		$this->pz = &get_instance();
		if($this->pz->islogin){
			$conditions['share_id'] = $share['share_id'];
			$conditions['user_id'] = $this->pz->cuser['uid'];
			$favsharedb = load_db('share/favshare');
			return $favsharedb->find($conditions);
		}
		
		return false;
	} 
	public function checkfav($share,$favshares){
		foreach ($favshares as $fav){
			if($share['share_id']==$fav['share_id']){
				return true;
			}
		}
		return false;
	}

	public function prepareshare($share){
		$share['link'] = host_url(site_url('detail/index?shareid='.$share['share_id']));
		$share['muilt'] = ($this->uimuilt&&$share['image_path_0']&&$share['image_path_1']&&$share['image_path_2']);

		$share['image0'] = thumburl($share['image_path_0'],'middle',$share['cloud']);
		$share['image1'] = thumburl($share['image_path_1'],'square',$share['cloud']);
		$share['image2'] = thumburl($share['image_path_2'],'square',$share['cloud']);
		$share['square'] = thumburl($share['image_path_0'],'square',$share['cloud']);
		$share['large'] = thumburl($share['image_path_0'],'large',$share['cloud']);
		$share['home'] = thumburl($share['image_path_0'],'home',$share['cloud']);

		$share['colorvalue'] = $this->colorsetting[$share['color']]?$this->colorsetting[$share['color']]:$this->colorsetting['gray'];
		if($share['reference_url']){
			$share['reflink'] = httpurl($share['reference_url']);
			$urls = parse_url($share['reflink']);
			$share['refhost'] = $urls['host'];
		}else{
			$share['refhost'] = $share['share_type'];
		}
		$share['item_type'] = $share['item_type']?$share['item_type']:'image';
		$share['isarticle'] = ($share['item_type']=='article')?true:false;
		$share['isvideo'] = ($share['item_type']=='video')?true:false;

		$share['ios'] = ($share['share_type']=='ios')?true:false;
		$share['android'] = ($share['share_type']=='android')?true:false;

		$comments = unserialize($share['comments']);
		if($this->comment_num){
			//$comments = unserialize($share['comments']);
			$comments =($comments)?array_slice($comments,0,$this->comment_num):null;
			if($comments){
				foreach ($comments as $key=>$com){
					$comments[$key]['comment_txt'] = load_api('puzzcode')->parse_message($com['comment_txt'],null,true);
				}
				$share['comments'] = $comments;
			}
		}
		if(array_length($comments)>0){
			$share['lastposter'] = $comments[0]['nickname'];
			$share['lastposter_id'] = $comments[0]['user_id'];
			$share['lastpost_time'] = $comments[0]['create_time'];
		}else{
			$share['lastposter'] = $share['user_nickname'];
			$share['lastposter_id'] = $share['user_id'];
			$share['lastpost_time'] = $share['create_time'];
		}

		if(!$share['isarticle']){
			if($share['width']&&$share['height']){
				//IE8 bug fix +2
				$share['height'] = ($this->wftwidth/$share['width'])*$share['height'];
			}else{
				$share['height'] = 0;
			}
			$share['long'] = $share['height']>800;
			$share['width'] = $this->wftwidth;
			$share['summary'] = trim($share['summary'])?sysSubStr($share['summary'], 100):$share['title'];
		}
		$tags = trimarray(explode(' ', $share['keyword']));
		$clean = array();
		$maxtag = array_length($tags);
		if($maxtag>0){
			$maxtag = $maxtag>3?3:$maxtag;
			for ($i=0;$i<$maxtag;$i++){
				$clean[] = $tags[$i];
			}
			unset($tags);
			$share['tags'] = $clean;
		}
		if($this->pz->cuser['uid']==$share['user_id']){
			$share['isowner'] = true;
		}
		return $share;
	}

	public function prepareTimelineshare($share){
		$share['link'] = site_url('detail/index?shareid='.$share['share_id']);
		$share['muilt'] = ($share['image_path_0']&&$share['image_path_1']);
		$share['image0'] = thumburl($share['image_path_0'],'large',$share['cloud']);
		$share['image1'] = thumburl($share['image_path_1'],'square',$share['cloud']);
		$share['image2'] = thumburl($share['image_path_2'],'square',$share['cloud']);
		$share['square'] = thumburl($share['image_path_0'],'square',$share['cloud']);

		$share['isarticle'] = ($share['item_type']=='article')?true:false;
		$share['isvideo'] = ($share['item_type']=='video')?true:false;
		$attaches = load_api('attachment')->findAttachByItem($share['item_id']);
		foreach ($attaches as $att){
			$path = $att['attachment'].'.'.$att['fileext'];
			$att['url'] = base_url().$att['attachment'].'_large.'.$att['fileext'];
			$att['square'] = base_url().$att['attachment'].'_square.'.$att['fileext'];
			if($path==$share['image_path_0']){
				$share['cover'] = $att;
			}else if($att['isimage']){
				$share['images'][] = $att;
			}else{
				$share['files'][] = $att;
			}
		}
		return $share;
	}

	public function prepareTimelineShares($shares){
		foreach ($shares as $key=>$share){
			$shares[$key] = $this->prepareTimelineshare($share);
		}
		return $shares;
	}

	public function add_ads($shares){
		$show = rand(0, 1);
		$setting = load_api('setting')->getSetting('ads');
		$ads=$setting['pinpage_ad'];
		if($show&&$ads){
			$ad = rand_pop($ads);
			if($ad){
				$ad_share['isad']=true;
				$ad_share['key']=$ad['key'];
				$ad_share['ad_name']=$ad['ad_name'];
				$ad_share['width']=$ad['width'];
				$ad_share['height']=$ad['height'];
				$ad_share['ad_position']='pinpage_ad';
				$index = rand(0, array_length($shares)-1);
				array_splice($shares, $index, 0, array($ad_share));
			}
		}
		return $shares;
	}


	public function search($conditions,$page,$pagesize,$order=null){
		$sharedb = load_db('share');
		return $sharedb->search($conditions,$page,$pagesize,null,$order);
	}

	public function getsamefromimg($uid){
		return load_db('share')->search_no_page(array('user_id'=>$uid,'type'=>'noarticle'),null,null,9);
	}

	public function getsamefromarticle($uid){
		return load_db('share')->search_no_page(array('user_id'=>$uid,'type'=>'article'),null,null,5);
	}

	public function getShareById($sid){
		return load_db('share')->getShareById($sid);
	}

	public function getItemidByShare($sid){
		$item = load_db('share')->find(array('share_id'=>$sid),null,' ptx_share.item_id ');
		if($item){
			return $item['item_id'];
		}
		return false;
	}

	public function getShareByAlbum($aid){
		return load_db('share')->search_no_page(array('album_id'=>$aid));
	}

	public function addviewnum($sid){
		return load_db('share')->addviewnum($sid);
	}

	public function findnextid($sid){
		$share = load_db('share')->find_one(array('find_next'=>$sid),'ptx_share.share_id ASC','share_id');
		return $share?$share['share_id']:false;
	}

	public function findprevid($sid){
		$share = load_db('share')->find_one(array('find_pre'=>$sid),'ptx_share.share_id DESC','share_id');
		return $share?$share['share_id']:false;
	}
	public function addOriginalShare(&$data){
		$sharedb = load_db('share');
		$itemdb = load_db('share/item');
		$itemdetaildb = load_db('share/itemdetail');
		if($data){
			if($itemid = $itemdb->addone($data)){
				if($data['itemdetail']){
					$data['itemdetail']['item_id']=$itemid;
					$itemdetaildb->addone($data['itemdetail']);
				}
				$data['sharedata']['item_id']=$itemid;
				$shareid = $sharedb->addone($data['sharedata']);
				$data['share_id']=$shareid;
				if($data['item_type']=='video'){
					load_api('event')->postvideo($data['user_id'],$data['title'],$shareid);
				}else{
					load_api('event')->postshare($data['user_id'],$data['title'],$shareid);
				}
				load_api('category')->add_totalshare($data['sharedata']['category_id']);
				return ($shareid)?$itemid:false;
			}
		}
		return false;
	}

	public function updateOriginalShare($share,$data){
		$sharedb = load_db('share');
		$itemdb = load_db('share/item');
		$itemdetaildb = load_db('share/itemdetail');
		if($data){
			if($itemdb->updateone($share['item_id'],$data)){
				if($data['itemdetail']){
					$itemdetaildb->updateone($share['item_id'],$data['itemdetail']);
				}
				$result = $sharedb->updateone($share['share_id'],$data['sharedata']);
				return $result;
			}
		}
		return false;
	}

	public function deleteShareById($id){
		$sharedb = load_db('share');
		if($share = $this->getShareById($id)){
			$condition['share_id'] = $id;
			if($sharedb->deleteByPk($id)){
				load_db('share/favshare')->delete($condition);
				load_db('comment')->delete($condition);
				if($share['user_id']==$share['poster_id']){
					$itemcon['item_id'] = $share['item_id'];
					load_db('share/item')->delete($itemcon);
					load_db('share/itemdetail')->delete($itemcon);
					load_api('attachment')->delAttachByItem($share['item_id']);
				}
				load_api('album')->update_album_cover($share['album_id']);
				load_db('user')->del_share($share['user_id']);
				load_api('welcome')->updateLastest20(7);
				load_api('category')->remove_totalshare($share['category_id']);
			}
		}
	}

	public function deleteShareByCondition($conditions){
		$sharedb = load_db('share');
		if($shares = $sharedb->search_no_page($conditions)){
			foreach ($shares as $share){
				$condition['share_id'] = $share['share_id'];
				if($sharedb->deleteByPk($share['share_id'])){
					load_db('share/favshare')->delete($condition);
					load_db('comment')->delete($condition);
					if($share['user_id']==$share['poster_id']){
						$itemcon['item_id'] = $share['item_id'];
						load_db('share/item')->delete($itemcon);
						load_db('share/itemdetail')->delete($itemcon);
						load_api('attachment')->delAttachByItem($share['item_id']);
					}
					load_api('album')->update_album_cover($share['album_id']);
					load_db('user')->del_share($share['user_id']);
				}
			}
		}
	}

	public function addlike($share_id,$uid){
		$favsharedb = load_db('share/favshare');
		$sharedb = load_db('share');
		$userapi = load_api('user');
		$share = $sharedb->getShareById($share_id);
		if($share['user_id'] == $uid){
			return 'like_self';
		}

		$liked = $favsharedb->find(array('share_id'=>$share_id,'user_id'=>$uid));
		if($liked){
			return 'like_already';
		}
		$addlike_result = $sharedb->add_like($share_id);
		$result = $favsharedb->add_one(array('share_id'=>$share_id,'user_id'=>$uid));
		if($result){
			$count = load_db('share/favshare')->findCount(array('user_id'=>$uid));
			$countlike = load_db('share/favshare')->findCountJoinByCon(array('share_user_id'=>$share['user_id']));
			$userapi->updateFavShareNum($uid,$count);
			$userapi->updateLike($share['user_id'],$countlike);
			load_api('event')->addlike($uid,$share['title'],$share_id,$share['user_id']);
			return true;
		}
		return $result;
	}

	public function removelike($share_id,$uid){
		$favsharedb = load_db('share/favshare');
		$sharedb = load_db('share');
		$userapi = load_api('user');
		$share = $sharedb->getShareById($share_id);
		if($share['user_id'] == $uid){
			return 'noexisted';
		}
		$result = $favsharedb->delete(array('share_id'=>$share_id,'user_id'=>$uid));
		if($result){
			$count = load_db('share/favshare')->findCount(array('user_id'=>$uid));
			$countlike = load_db('share/favshare')->findCountJoinByCon(array('share_user_id'=>$share['user_id']));
			$userapi->updateFavShareNum($uid,$count);
			$userapi->updateLike($share['user_id'],$countlike);
			$sharedb->remove_like($share_id);
			return true;
		}
		return $result;
	}

	private function getColorIndex($attach){
		$dest_file_path = BASEPATH.$attach['attachment'].'.'.$attach['fileext'];
		$imagelib = &load_class('ImageLib');
		return $imagelib->sample_color($dest_file_path);
	}

	private function checkMiddlePic($attach){
		$sourcepath = BASEPATH.$attach['attachment'].'.'.$attach['fileext'];
		$dest_file_path = BASEPATH.$attach['attachment'].'_middle.'.$attach['fileext'];
		if(!file_exists($dest_file_path)){
			$imagelib = &load_class('ImageLib');
			$setting = load_api('setting')->getUploadSetting();
			$wftwidth = $setting['wftwidth']?$setting['wftwidth']:220;
			$imagelib->create_thumb($sourcepath, 'middle', $wftwidth);
		}
	}

	public function mvBannedUserPostToDeleted($uid){
		$itemdb = load_db('share/item');
		$itemdb->update(array('user_id'=>$uid),array('is_deleted'=>'1'));
	}
	public function unBannedUserPostFromDeleted($uid){
		$itemdb = load_db('share/item');
		$itemdb->update(array('user_id'=>$uid),array('is_deleted'=>'0'));
	}

	public function updateItem($coverfile,$itemid){
		$data = array();
		$itemdb = load_db('share/item');
		$itemdetaildb = load_db('share/itemdetail');
		$detaildata = array();
		$data['total_images']=$coverfile['total'];
		if($coverfile['findcover']){
			$data['item_type']=$coverfile['item_type'];
			$data['width']=$coverfile['width'];
			$data['height']=$coverfile['height'];
			$data['share_type']=$coverfile['share_type'];
			$data['image_path_0']=$coverfile['attachment'].'.'.$coverfile['fileext'];
			$data['color']=$this->getColorIndex($coverfile);
			$this->checkMiddlePic($coverfile);
			$api = load_api('attachment');
			$images = $api->findSubImageCoverByItem($itemid,$coverfile['aid']);
			if(array_length($images)==2){
				$data['image_path_1']=$images[0]['attachment'].'.'.$images[0]['fileext'];
				$data['image_path_2']=$images[1]['attachment'].'.'.$images[1]['fileext'];
			}else{
				$data['image_path_1']='';
				$data['image_path_2']='';
			}

			if($coverfile['remoteimgs']){
				$itemdetail = $itemdetaildb->find(array('item_id'=>$itemid));
				$intro = $itemdetail['intro'];
				foreach($coverfile['remoteimgs'] as $img) {
					$intro = str_replace('[remoteimg]'.$img['remote'].'[/remoteimg]', '[attachimg]'.$img['aid'].'[/attachimg]', $intro);
				}
				$detaildata['intro']=$intro;
			}

			if($coverfile['prourl']){
				$detaildata['promotion_url']=$coverfile['prourl'];
			}


			if($coverfile['pitemid']){
				$detaildata['reference_itemid']=$coverfile['pitemid'];
			}

		}else{
			$data['item_type']='article';
			$data['share_type']='upload';
			$data['image_path_0']='';
			$data['image_path_1']='';
			$data['image_path_2']='';
			$return['width']='';
			$return['height']='';
			$data['color'] = '';

			$attrs = array('item_id','intro','intro_search','reference_url','reference_itemid','reference_channel','promotion_url');
			$detaildata['reference_itemid'] = '';
			$detaildata['reference_channel'] = '';
			$detaildata['promotion_url'] = '';
		}

		$itemdetaildb->update(array('item_id'=>$itemid),$detaildata);
		return $itemdb->update(array('item_id'=>$itemid),$data);
	}

	public function afterAddComment($sid,$total_comments,$comments){
		$this->updateshare($sid,array('lastcomment_time'=>TIMESTAMP,'total_comment'=>$total_comments,'comments'=>serialize($comments)));
	}

	function digist($share_id,$type='g'){
		switch ($type) {
			case 'g':
				$dtype=1;
				break;
			default: //remove digist
				$dtype=0;
				break;
		}
		return load_db('share')->update(array('share_id'=>$share_id), array('dtype'=>$dtype));
	}
	
	function maketop($share_id,$type='g'){
		switch ($type) {
			case 'g':
				$dtype=2;
				break;

			case 'c':
				$dtype=3;
				break;
			default: //remove top
				$dtype=0;
				break;
		}
		
		return load_db('share')->update(array('share_id'=>$share_id), array('dtype'=>$dtype));
	}
	
}
